#!/bin/bash

BACKUP_DIR=""
backup_time=$(date '+%Y%m%d%H%M')
log=${BACKUP_DIR}/backup.log
MYSQL_HOST=""
MYSQL_USER=
MYSQL_PW=''
DISK_AVAILABLE=$(df -h | fgrep "" | awk '{print $4}')

# 查找并清理文件
function clean() {
   cd ${BACKUP_DIR} && tar zcf ${BACKUP_DIR}/${backup_time}.tar.gz ${BACKUP_DIR}/${backup_time}.sql && rm -rf ${BACKUP_DIR}/${backup_time}.sql
   find ${BACKUP_DIR} -name "*.tar.gz" -mtime +14 -exec rm -rf {} \;
}

# 备份函数
function backup() {
   echo "###################################" >>$log
   date '+%Y-%m-%d %H:%M' >>$log

   /workspace/mysql/bin/mysqldump -h ${MYSQL_HOST} -u${MYSQL_USER} --single-transaction --routines --triggers --events -p${MYSQL_PW} -A >${BACKUP_DIR}/${backup_time}.sql
   if [ $? -ne 0 ]; then
      echo "backup databases failed !" >>$log
      exit 1
   else
      date '+%Y-%m-%d %H:%M' >>$log
      echo "backup databases seccessful ." >>$log
   fi

   echo "###################################" >>$log
}

# 检测磁盘容量及信息，每次全备增量为60G，预留buffer 10G。磁盘为241，即> 171的时候停止备份，避免失败。
function checkdisk() {
   if [[ "${DISK_AVAILABLE}" > "171G" ]]; then
      backup
   else
      echo "disk available space is low than 70G ! " >>$log
   fi

}

function main() {
   checkdisk
   clean
}

main